import React from 'react';
import { history } from 'umi';
import { apiAccountRefreshToken, apiGetCurrentInfo } from '@/api/account.api';
import { ke } from '@/plugins/ke';
import log from 'loglevel';
import 'bootstrap-grid/dist/grid.min.css';
import { useModel } from '@@/plugin-model/useModel';

process.env.NODE_ENV === 'development' ? log.enableAll() : log.disableAll();

export interface CurrentAccountInfo {
  id?: number;
  nickname?: string;
  username?: string;
  avatar?: string;
  phone?: string;
  email?: string;
  login_ip?: string;
  login_time?: string;
  create_time?: string;
}

export interface InitialResponse {
  title?: string;
  userinfo?: CurrentAccountInfo;
  permissions?: string[];
}

const loginExpireCheck = () => {
  const time = ke.getTimestamp();
  const loginExpire: number = Number(localStorage.getItem('login_expire'));

  if (loginExpire < time) {
    // 登录超时
    throw new Error('登录超时');
  } else if (loginExpire - time <= 900) {
    // 到期15分钟前,延长令牌有效时间
    apiAccountRefreshToken()
      .then(({ data }: any) => {
        localStorage.setItem('login_expire', time + data.expire_in);
      })
      .catch((e: any) => {
        console.warn('令牌更新失败', e.message);
      });
  }
};

// 状态初始化
export const getInitialState = async (): Promise<InitialResponse> => {
  let res: InitialResponse = {
    title: 'EasyAdmin',
  };
  let userInfo: CurrentAccountInfo | undefined;

  window.onfocus = async () => {
    if (history.location.pathname !== '/login') {
      try {
        loginExpireCheck();

        const { data } = await apiGetCurrentInfo();

        userInfo = data.info;

        return {
          ...res,
          userinfo: userInfo,
          permissions: data.permissions,
        };
      } catch (e) {
        history.push('/login');
      }
    }
  };

  if (history.location.pathname !== '/login') {
    try {
      loginExpireCheck();

      const { data } = await apiGetCurrentInfo();
      //
      // load()

      userInfo = data.info;

      return {
        ...res,
        userinfo: userInfo,
        permissions: data.permissions,
      };
    } catch (e) {
      history.push('/login');
    }
  }

  return res;
};
